<script setup>
import { merge, forEach } from 'lodash-es';
import { useRequest } from '@/hooks/requestHooks';
import { useDownload } from '@/hooks/tool.js';
import { useRoute } from '@/router/index.js';
import { getInstitutionInfo, getInstitutionUsageEnergy, getType } from '@/api/index.js';
import { TableList } from '@/components/MainComponents.js';
import DateChart from '@/views/components/DateChart.vue';
import { useWatch } from '@/hooks/useWatch';
const route = useRoute();
const queryParams = ref({
  areaId: route.query.code,
  dateType: '',
  dateStart: '',
  dateEnd: '',
});
const chartRef = ref(null);
const energyType = ref('总');
const engTypes = [
  { value: 'ALL', label: '总', unit: 'tce' },
  // { value: 'ELECTRICITY', label: '电', unit: 'KWh' },
  // { value: 'WATER', label: '水', unit: 't' },
  // { value: 'AIR', label: '气', unit: 'm³' },
  // { value: 'WARM', label: '暖', unit: 'KJ' },
];
const unitList = {
  总: 'tce',
  // 电: 'KWh',
  // 水: 't',
  // 气: 'm³',
  // 暖: 'KJ',
};
const typeList = {
  总: 'total',
  // 电: 'electricity',
  // 水: 'water',
  // 气: 'air',
  // 暖: 'warm',
};
const chartOpts = ref({
  // title: {
  //   text: '能耗趋势分析',
  //   ...basicTitle,
  // },
  color: ['#4992ff', '#f58819'],
  yAxis: [
    { name: `单位：${unitList[energyType.value]}` },
    {
      type: 'value',
      show: false,
    },
  ],
  dataset: {
    dimensions: ['time', { name: 'total', displayName: '能耗总量' }, { name: 'same', displayName: '能耗趋势' }],
    source: [],
  },
  series: Array.from({ length: 2 }, (_, idx) => {
    return idx === 0
      ? {
          type: 'bar',
          barWidth: 25,
          yAxisIndex: 0,
        }
      : {
          type: 'line',
          smooth: true,
          showSymbol: false,
          yAxisIndex: 1,
        };
  }),
  tooltip: {},
  dataZoom: [{ xAxisIndex: [0, 1] }, { xAxisIndex: [0, 1] }],
});
const pageObj = ref({
  pageSize: 10,
  pageNum: 1,
});
const columObj = ref({
  index: true,
  columnData: [
    {
      text: true,
      prop: 'time',
      label: '统计时间',
    },
    {
      text: true,
      prop: 'total',
      label: '总能耗（tce）',
    },
    // {
    //   text: true,
    //   prop: 'electricity',
    //   label: '电能耗（kWh）',
    // },
    // {
    //   text: true,
    //   prop: 'water',
    //   label: '水能耗（t）',
    // },
    // {
    //   text: true,
    //   prop: 'air',
    //   label: '气能耗（m³）',
    // },
    // {
    //   text: true,
    //   prop: 'warm',
    //   label: '暖能耗（KJ）',
    // },
  ],
});
const tableData = ref([]);
const detailsData = ref([]);
const detailsList = ref([
  { label: '机构名称', key: 'buildingName' },
  { label: '机构代码', key: 'socialId' },
  { label: '机构地址', key: 'areaAddress' },
  { label: '机构类型', key: 'branchType' },
  { label: '总能耗（tce）', key: 'total' },
  // { label: '电能耗（kWh）', key: 'electricity' },
  // { label: '水能耗（t）', key: 'water' },
  // { label: '气能耗（m³）', key: 'air' },
  // { label: '暖能耗（KJ）', key: 'warm' },
  // { label: '总电表户号', key: 'eleGauges' },
  // { label: '总水表户号', key: 'waterGauges' },
  // { label: '总气表户号', key: 'airGauges' },
  // { label: '总供暖表户号', key: 'warmGauges' },
]);
useRequest(getType, {
  onSuccess: res => {
    res.forEach(n => {
      let obj = { label: `${n.energyName}能耗（${n.energyUnit}）`, key: n.fileName };
      detailsList.value.push(obj);
      let obj2 = {
        value: n.fileName,
        label: n.energyName,
        unit: n.energyUnit,
      };
      engTypes.push(obj2);
      unitList[n.energyName] = n.energyUnit;
      typeList[n.energyName] = n.fileName;
      let obj3 = {
        text: true,
        prop: n.fileName,
        label: `${n.energyName}能耗（${n.energyUnit}）`,
      };
      columObj.value.columnData.push(obj3);
    });
  },
});
useRequest(getInstitutionInfo, {
  defaultParams: [{ institutionCode: route.query.code }],
  onSuccess: res => {
    let obj2 = {};
    forEach(res?.data?.gaugesList, (n, i) => {
      obj2[`gaugesNum${i}`] = n.gaugesNum;
      console.log('[ n,i ] >', n, i);
      let obj = {
        label: n.gaugesName,
        key: `gaugesNum${i}`,
      };
      detailsList.value.push(obj);
    });
    detailsData.value = merge(res?.data?.eachTypeEnergyVO, res?.data?.enBuilding, obj2);
    console.log('[ obj2, ] >', obj2, detailsData.value);
  },
  // manual: true,
});
const [res, loading, run] = useRequest(getInstitutionUsageEnergy, {
  defaultParams: [queryParams.value],
  manual: true,
  onSuccess: res => {
    let arr = forEach(res.data, n => {
      n.same = n[typeList[energyType.value]];
    });
    chartOpts.value.dataset.source = arr;
    tableData.value = res.data.slice(0, 10);
    chartOpts.value.tooltip.formatter = params => {
      if (Array.isArray(params) && params.length > 0) {
        params.splice(1, 1);
        let str = `<div class="u-mb5">${params[0].axisValue}</div>`;
        forEach(params, e => {
          let seriesName = e.seriesName;
          const value = e.value[e.dimensionNames[e.encode.y]] ?? '--';
          str += `<ul class="u-df-spb u-mb5"><li>${e.marker}${seriesName}</li><li class="u-ml30">${value}</li></ul>`;
        });
        return str;
      }
      return '';
    };
  },
});
const getList = e => {
  pageObj.value.pageNum = e.page;
  pageObj.value.pageSize = e.limit;
  tableData.value = chartOpts.value.dataset?.source.slice((e.page - 1) * e.limit, e.page * e.limit);
};
const handleChart = dateParams => {
  queryParams.value.dateStart = dateParams.startTime;
  queryParams.value.dateEnd = dateParams.endTime;
  queryParams.value.dateType = dateParams.dateType;
  run(queryParams.value);
};
const handleExport = () => {
  useDownload('/energyservice/overviewAnalysis/exportInstitutionUsageEnergy', queryParams.value, `能耗趋势分析.xlsx`);
};
useWatch(energyType, n => {
  if (n) {
    chartOpts.value.yAxis[0].name = `单位：${unitList[n]}`;
    chartOpts.value.dataset.dimensions[1].name = typeList[energyType.value];
    run(queryParams.value);
  }
});
onMounted(() => {
  queryParams.value.dateStart = chartRef.value.dateParams.startTime;
  queryParams.value.dateEnd = chartRef.value.dateParams.endTime;
  queryParams.value.dateType = chartRef.value.dateParams.dateType;
  run(queryParams.value);
});
</script>
<template>
  <div>
    <div class="u-df-spb u-mb10">
      <span class="u-prim-text">名录详情</span>
      <i class="el-icon-back u-prim-text u-fs20 u-back" @click="$router.replace('entDirectory')"></i>
    </div>
    <div class="u-base-fg u-p20 u-mb20">
      <div class="u-mb20">名录详情</div>
      <el-descriptions title="" :column="5" size="small" border>
        <el-descriptions-item v-for="(item, index) in detailsList" :key="index">
          <template slot="label">
            <div class="u-df-st">
              <div class="info-descriptionsItem">{{ item.label }}</div>
            </div>
          </template>
          <div class="info-descriptionsItem">{{ detailsData?.[item.key] ?? '--' }}</div>
        </el-descriptions-item>
      </el-descriptions>
    </div>
    <div class="u-base-fg u-df-st u-p20 u-mb20" style="height: 400px; position: relative">
      <span style="position: absolute; top: 40px">能耗趋势分析</span>
      <el-select v-model="energyType" class="energyType" clearable size="mini">
        <el-option v-for="item in engTypes" :key="item.label" :label="item.label" :value="item.label"></el-option>
      </el-select>
      <DateChart
        ref="chartRef"
        v-loading="loading"
        class="u-p20 u-base-fg"
        formStyle="u-df-ed"
        style="height: 360px; width: 100%"
        :extraOpts="chartOpts"
        @handleDateParams="handleChart"
      />
    </div>
    <div class="contBox">
      <div class="u-df-spb mb20">
        <span>能耗趋势分析列表</span>
        <el-button type="primary" plain size="small" @click="handleExport">导出</el-button>
      </div>
      <TableList
        v-loading="loading"
        :total="res?.length ?? 0"
        :tableData="tableData"
        :pageObj="pageObj"
        :columObj="columObj"
        @getList="getList"
      />
    </div>
  </div>
</template>
<style lang="scss" scoped>
.energyType {
  position: absolute;
  top: 40px;
  right: 420px;
  width: 100px;
}
</style>
